<template>
  <div class="ai-bot-container">
    <div class="main-content">
      <div class="content-header">
        <h1 class="page-title">AI 聊天机器人</h1>
        <p class="page-subtitle">与智能AI进行自然对话，获取信息和帮助</p>
      </div>

      <div class="chat-section">
        <div class="chat-container">
          <div class="chat-messages" ref="chatMessages">
            <div
              v-for="message in messages"
              :key="message.id"
              :class="['message', message.sender]"
            >
              <div class="message-avatar">
                <div
                  class="avatar"
                  :class="{ user: message.sender === 'user', bot: message.sender === 'bot' }"
                >
                  {{ message.sender === 'user' ? '👤' : '🤖' }}
                </div>
              </div>
              <div class="message-content">
                <div class="message-text">{{ message.text }}</div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>

            <div v-if="isTyping" class="message bot typing">
              <div class="message-avatar">
                <div class="avatar bot">🤖</div>
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>

            <div v-if="messages.length === 0" class="welcome-message">
              <div class="avatar bot">🤖</div>
              <div class="welcome-text">
                <h3>你好！我是你的AI助手</h3>
                <p>我可以帮助你解答问题、提供信息和建议。请输入你的问题开始对话吧！</p>
              </div>
            </div>
          </div>

          <div class="chat-input-container">
            <div class="input-actions">
              <button class="action-btn" @click="clearChat">
                🗑️ 清空
              </button>
              <button class="action-btn" @click="toggleSettings">
                ⚙️ 设置
              </button>
            </div>

            <div class="input-group">
              <input
                type="text"
                v-model="inputMessage"
                @keypress.enter="sendMessage"
                placeholder="输入你的问题..."
                :disabled="isTyping"
              />
              <button
                class="send-btn"
                @click="sendMessage"
                :disabled="!inputMessage.trim() || isTyping"
              >
                {{ isTyping ? '⏳' : '📤' }}
              </button>
            </div>
          </div>

          <div v-if="showSettings" class="chat-settings">
            <div class="settings-content">
              <h4>聊天设置</h4>
              <div class="setting-item">
                <label>AI模型</label>
                <select v-model="selectedModel">
                  <option value="gpt-3.5">GPT-3.5 Turbo</option>
                  <option value="gpt-4">GPT-4</option>
                  <option value="claude">Claude</option>
                </select>
              </div>
              <div class="setting-item">
                <label>温度</label>
                <input
                  type="range"
                  v-model="temperature"
                  min="0"
                  max="1"
                  step="0.1"
                />
                <span class="value-display">{{ temperature }}</span>
              </div>
              <div class="setting-item">
                <label>最大长度</label>
                <input
                  type="number"
                  v-model="maxTokens"
                  min="50"
                  max="4000"
                />
              </div>
              <button class="save-settings" @click="saveSettings">保存设置</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'

// 聊天状态
const messages = ref([])
const inputMessage = ref('')
const isTyping = ref(false)
const showSettings = ref(false)

// 设置状态
const selectedModel = ref('gpt-3.5')
const temperature = ref('0.7')
const maxTokens = ref('2000')

// 模块初始化
onMounted(() => {
  console.log('AI Bot module loaded')

  // 加载历史消息
  loadChatHistory()

  // 添加欢迎消息
  addBotMessage('你好！我是你的AI助手。我可以帮助你解答问题、提供信息和建议。')
})

/**
 * 格式化当前时间
 */
function formatTime(date = new Date()) {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 添加用户消息
 */
function addUserMessage(text) {
  messages.value.push({
    id: Date.now(),
    text,
    sender: 'user',
    time: formatTime()
  })
  scrollToBottom()
}

/**
 * 添加机器人消息
 */
function addBotMessage(text) {
  messages.value.push({
    id: Date.now(),
    text,
    sender: 'bot',
    time: formatTime()
  })
  scrollToBottom()
}

/**
 * 发送消息
 */
async function sendMessage() {
  const text = inputMessage.value.trim()
  if (!text || isTyping.value) return

  addUserMessage(text)
  inputMessage.value = ''
  isTyping.value = true

  // 模拟AI响应
  await simulateAIResponse(text)

  isTyping.value = false
  saveChatHistory()
}

/**
 * 模拟AI响应
 */
async function simulateAIResponse(userMessage) {
  // 模拟不同类型的响应
  const responses = [
    '这是一个很有趣的问题！让我来帮你分析一下。',
    '根据我的理解，这个问题可以从以下几个方面来看...',
    '我建议你可以尝试以下几种方法：',
    '这个问题涉及到一些专业知识，让我详细解释一下：',
    '你的想法很有创意！我完全同意你的观点。',
    '这是一个值得深思的问题。让我为你提供一些建议...',
    '从技术角度来看，这个问题有以下几种解决方案：'
  ]

  const delay = Math.random() * 2000 + 1000
  await new Promise(resolve => setTimeout(resolve, delay))

  const response = responses[Math.floor(Math.random() * responses.length)]
  addBotMessage(response)
}

/**
 * 滚动到底部
 */
function scrollToBottom() {
  nextTick(() => {
    const container = this.$refs?.chatMessages
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}

/**
 * 清空聊天
 */
function clearChat() {
  if (confirm('确定要清空所有聊天记录吗？')) {
    messages.value = []
    addBotMessage('聊天记录已清空。有什么我可以帮你的吗？')
    localStorage.removeItem('ai-chat-history')
  }
}

/**
 * 切换设置面板
 */
function toggleSettings() {
  showSettings.value = !showSettings.value
}

/**
 * 保存设置
 */
function saveSettings() {
  const settings = {
    model: selectedModel.value,
    temperature: temperature.value,
    maxTokens: maxTokens.value
  }
  localStorage.setItem('ai-bot-settings', JSON.stringify(settings))
  showSettings.value = false
  alert('设置已保存！')
}

/**
 * 加载聊天历史
 */
function loadChatHistory() {
  try {
    const history = localStorage.getItem('ai-chat-history')
    if (history) {
      messages.value = JSON.parse(history)
    }
  } catch (error) {
    console.error('Failed to load chat history:', error)
  }
}

/**
 * 保存聊天历史
 */
function saveChatHistory() {
  try {
    localStorage.setItem('ai-chat-history', JSON.stringify(messages.value))
  } catch (error) {
    console.error('Failed to save chat history:', error)
  }
}
</script>